package com.example.demo.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.system.configure.ResultConfigure;
import com.example.demo.system.entity.User;
import com.example.demo.system.service.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author XinYiFan
 * @since 2023-04-06
 */
@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @PostMapping("/login")
    public ResultConfigure<Map<String,Object>> login(@RequestBody User user){
        Map<String,Object> data = userService.login(user);
        if(data != null){
            return ResultConfigure.success(data);
        }
        return ResultConfigure.fail(20001,"用户名或者密码错误");
    }
    @GetMapping("/info")
    public ResultConfigure<Map<String,Object>> getUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        System.out.printf(token);
        //根据token从redis获取用户信息
        Map<String,Object> data = userService.getUserInfo(token);

        if(data != null){
            return ResultConfigure.success(data);
        }
        return ResultConfigure.fail(20002,"用户信息无效，请重新登录");
    }
    @PostMapping("/logout")
    public ResultConfigure<Map<String ,Object>> logout(@RequestParam("T-Token") String token){
        userService.logout(token);
        return ResultConfigure.success();
    }
    @GetMapping("/list")
    public ResultConfigure<Map<String,Object>> getUserList(@RequestParam(value = "username",required = false) String username,
                                                  @RequestParam(value = "phone",required = false) String phone,
                                                  @RequestParam(value = "pageNo") Long pageNo,
                                                  @RequestParam(value = "pageSize") Long pageSize){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(username),User::getUsername,username);
        wrapper.eq(StringUtils.hasLength(phone),User::getPhone,phone);
        wrapper.orderByDesc(User::getId);
        Page<User> page = new Page<>(pageNo,pageSize);
        userService.page(page,wrapper);
        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return ResultConfigure.success(data);
    }

}
